<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Entity\UserFacebook;
use Application\Entity\User;
use Application\Entity\Friend;
use Zend\Mvc\Controller\Plugin\Redirect;
use Zend\Authentication\AuthenticationService;
use Zend\Log\Logger;
use Zend\Log\Writer\Stream;
use Zend\View\Model\JsonModel;
use Application\Component\FriendComponent;
use Application\Component\UserComponent;
use Application\Component\UserFacebookComponent;
use DateTime;

class FriendController extends AbstractActionController
{

    protected $em;

    protected $storage;

    protected $authservice;

    protected $userComponent;

    protected $friendComponent;

    protected $userFacebookComponent;
    protected $user;

    public function init()
    {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
            $this->friendComponent = new FriendComponent($this->em);
            
            $this->userComponent = new UserComponent($this->em);
            $this->userFacebookComponent = new UserFacebookComponent($this->em);
        }
        $this->user = $this->identity();
        //var_dump($this->user);
        return $this->em;
    }
    
    /**
     * Use to check, if a given user is friend of the connected one, or if any demand have been sent in any size
     */
    public function getUserStatusAction(){
        $this->init();
        $id = (int)$this->params()->fromRoute('id');//User concerned id
        $results = array();
        $friend1 = null;
        $friend2 = null;
        if($this->user!=null){
            $friends1 = $this->friendComponent->listByUser($this->user==null?0:$this->user->uid, 0, 1, -1, $id);
            $friends2 = $this->friendComponent->listByUser($id, 0, 1, -1, $this->user==null?0:$this->user->uid);
            
            if($friends1!=null&&count($friends1)>0) $friend1 = $friends1[0];
            if($friends2!=null&&count($friends2)>0) $friend2 = $friends2[0];
        }
        if($friend1!=null) $results["friend1"] = $friend1->getJson();
        if($friend2!=null) $results["friend2"] = $friend2->getJson();
        $results["now"] = (new DateTime("now"))->format("Y-m-d H:i:s");
        $results["success"] = "Loaded";
        return new JsonModel($results);
    }

    public function listAction()
    {
        $this->init();
        $id = (int)$this->params()->fromRoute('id');//User concerned id
		$offset = (int)$this->params()->fromRoute('offset'); //
		$limit = (int)$this->params()->fromRoute('limit'); //
		$friends = $this->friendComponent->listByUser($id, $offset, $limit, 1);
		$results = array();
		foreach ($friends as $row){
		    $results[] = $row->getJson();
		}
        return new JsonModel(
            array(
                "friends"=>$results,
    		    'now'=>(new DateTime("now"))->format("Y-m-d H:i:s"),
            )
        );
    }

    public function listdemandsAction()
    {
        $this->init();
        $id = (int)$this->params()->fromRoute('id');//User concerned id
		$offset = (int)$this->params()->fromRoute('offset'); //
		$limit = (int)$this->params()->fromRoute('limit'); //
		$friends = $this->friendComponent->listByUser(null, $offset, $limit, 0, $id);
		$results = array();
		foreach ($friends as $row){
		    $results[] = $row->getJson();
		}
        return new JsonModel(
            array(
                "friends"=>$results,
    		    'now'=>(new DateTime("now"))->format("Y-m-d H:i:s"),
            )
        );
    }

    
    public function askdemandAction()
    {
        $this->init();
        $message = array();
        $id = (int)$this->params()->fromRoute('id');//User concerned id
        $concerned = $this->userComponent->get($id);
        $row = null;
        $demand = null;
        if($this->user!=null && $concerned!=null){
            //Check first if the concerned user didn't send a demand to the concerned
            $demandsSent = $this->friendComponent->listByUser($this->user->uid, 0, 0, -1, $id);
            if($demandsSent!=null && count($demandsSent)>0){
                //The user has already sent a demand
                $row = $demandsSent[0];
                //TODO
            }else{
                $demandsReceived = $this->friendComponent->listByUser($id, 0, 0, -1, $this->user->uid);
                if($demandsReceived!=null && count($demandsReceived)>0){
                	//The user has already been invited by the other, or they where friends before
                	
                    $row = new Friend();
                    $row->userFrom = $this->user;
                    $row->userTo = $concerned;
                    $row->confirmed = 1;
                    $this->friendComponent->insert($row);
                    $row->confirmAt = $row->createdAt;
                    $this->friendComponent->update($row);
                    
                    $demand = $demandsReceived[0];
                    $demand->confirmed = 1;
                    $demand->confirmAt = $row->confirmAt;
                    $this->friendComponent->update($demand);
                    
                }else{
                	//Send a new invitation
                	$row = new Friend();
                	$row->userFrom = $this->user;
                	$row->userTo = $concerned;
                	$row->confirmed = 0;
                	$this->friendComponent->insert($row);
                }
            }
            if($row!=null) $message["friend1"] = $row->getJson();
            if($demand!=null) $message["friend2"] = $demand->getJson();
            $message["success"] = "confirmed";
        }else{
            $message["error"] = "not allowed";
        }
        return new JsonModel($message);
    }
    
    public function acceptdemandAction()
    {
        $now = new \DateTime("now");
        $this->init();
        $message = array();
        $id = (int)$this->params()->fromRoute('id');//The id of the demand to confirm
        $demand = $this->friendComponent->get($id);//The demand the user want to accept
        //var_dump($demand);
        $row = null;
        if($this->user==null || $demand==null || $demand->userTo==null || $demand->userFrom==null || $demand->userTo->uid!=$this->user->uid){
            //Not allowed
            $demand = null;
            $message["error"] = "not allowed";
        }else{
            $demandsSent = $this->friendComponent->listByUser($this->user->uid, 0, 0, -1, $demand->userFrom->uid);
            if($demandsSent!=null && count($demandsSent)>0){
            	//The user has also already sent a demand (normally this case should not happen if others things walk correctly)
            	$row = $demandsSent[0];
            	if(!$row->confirmed){
            	    $row->confirmed = 1;
            	    $row->confirmAt = $now;
            	    $this->friendComponent->update($row);
            	}
            	if(!$demand->confirmed){
            	    $demand->confirmed = 1;
            	    $demand->confirmAt = $now;
            	    $this->friendComponent->update($demand);
            	}
            	$message["friend1"] = $row->getJson();
            	$message["friend2"] = $demand->getJson();
            	$message["success"] = "confirmed";
            }else{
                $row = new Friend();
                $row->userFrom = $this->user;
                $row->userTo = $demand->userFrom;
                $row->confirmed = 1;
            	$row->confirmAt = $now;
                $this->friendComponent->insert($row);
            	if(!$demand->confirmed){
            	    $demand->confirmed = 1;
            	    $demand->confirmAt = $now;
            	    $this->friendComponent->update($demand);
            	}
            	$message["friend1"] = $row->getJson();
            	$message["friend2"] = $demand->getJson();
            	$message["success"] = "confirmed";
            }
        }
        return new JsonModel($message);
        
    }
    
    public function refusedemandAction()
    {
        $now = new \DateTime("now");
        $this->init();
        $message = array();
        $id = (int)$this->params()->fromRoute('id');//The id of the demand to refuse
        $demand = $this->friendComponent->get($id);//The demand the user want to accept
        $row = null;
        if($this->user==null || $demand==null || $demand->userTo==null || $demand->userFrom==null || $demand->userTo->uid!=$this->user->uid){
            //Not allowed
            $demand = null;
            $message["error"] = "not allowed";
        }else{
            $friends = $this->friendComponent->listByUser($this->user->uid, 0, 0, -1, $demand->userFrom->uid);
            if($friends!=null && count($friends)>0){//They were already friends
                //Delete the friend here
                $friend = $friends[0];
                $this->friendComponent->delete($friend);
            }else{
            }
                
            $demand->confirmed = 2;
            $demand->confirmAt = $now;
            $this->friendComponent->update($demand);//TODO Should I delete the demand instead?
            $message["friend2"] = $demand->getJson();
            $message["success"] = "declined";
        }
        return new JsonModel($message);
        
    }
    
    /**
     * Delete a friend given by it's id as parameter
     * @return \Zend\View\Model\JsonModel
     */
    public function deleteAction()
    {
        $now = new \DateTime("now");
        $this->init();
        $message = array();
        $id = (int)$this->params()->fromRoute('id');//User concerned id
        $friend = $this->friendComponent->get($id);//The demand the user want to accept
        $row = null;
        if($this->user==null || $friend==null || $friend->userTo==null || $friend->userFrom==null || $friend->userFrom->uid!=$this->user->uid){
            //Not allowed
            $friend = null;
            $message["error"] = "not allowed";
        }else{
            $friends2 = $this->friendComponent->listByUser($friend->userTo->uid, 0, 0, -1, $this->user->uid);
            $friend2 = null;
            if($friends2!=null && count($friends2)>0){//They were already friends
                //Delete the friend here
                $friend2 = $friends2[0];
                $friend2->confirmed = 2;
                $friend2->confirmAt = $now;
                $this->friendComponent->update($friend2);//TODO Should I delete the demand instead?
                
            }else{
            }
            
            $this->friendComponent->delete($friend);
            
            if($friend2!=null) $message["friend2"] = $friend2->getJson();
            $message["success"] = "declined";
        }
        return new JsonModel($message);
        
    }
 
}
